<?php

namespace app\admin\controller;

use app\common\model\MoneybagLogModel;
use app\common\model\TokenMoneyLogModel;
use cmf\controller\AdminBaseController;
use think\Db;

/*车品超市 订单*/

class GoodsOrderController extends AdminBaseController
{
    //订单列表
    public function index()
    {
        $map = [];
        //车品超市订单状态
        $order_statusArr = config('config.order_status');
        //状态
        $order_status = input('order_status','');
        if ($order_status != '') {
            $map[] = ['status', '=', $order_status];
        }
        $status_option = '';
        foreach ($order_statusArr as $key => $order_statu) {
            if ($order_status != '') {
                $selected = $key == $order_status ? 'selected' : '';
            } else {
                $selected = '';
            }
            $status_option .= <<<TPL
            <option value="{$key}" {$selected} >{$order_statu}</option>
TPL;
        }
        //关键字
        $keywords = input('keywords', '');
        if (!empty($keywords)) {
            $map[] = ['goods_order_no|user_login|user_email', 'like', '%' . $keywords . '%'];
        }
        $datas = db('market_order')
            ->alias('o')
            ->field('o.id,o.uid,o.goods_order_no,o.order_no,o.address,o.ordertime,o.money,o.status,u.user_login,u.user_email')
            ->where($map)
            ->leftJoin('jzb_user u', 'o.uid = u.id')
            ->order('id desc')
            ->paginate(10);
        return view('', compact('datas', 'status_option'));
    }

    //查看订单详情
    public function seeOrder()
    {
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('订单号错误');
        }
        //查询订单
        $data = db('market_order')->find($id);
        //查看订单详情
        $details = db('market_order_details')->where('order_id', $id)->select();
        //查看订单取消和退款退货表
        if (!empty($data['backid'])) {
            $backData = db('marketorder_back')->find($data['backid']);
            //图片处理
            if (!empty($backData['img'])) {
                $backData['img'] = explode('|', $backData['img']);
            }
        } else {
            $backData = '';
        }
        return view('', compact('data', 'details', 'backData'));
    }

    //订单发货 填写物流信息
    public function sendOrder()
    {
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            $this->error('订单号错误');
        }
        if (isPost()) {
            $param = input();
            if (empty($postname = $param['postname']) || empty($postno = $param['postno'])) {
                $this->error('快递选项不能为空');
            }
            //加入快递 更改状态已发货待收货
            db('market_order')
                ->where('id', $param['id'])
                ->update(['postname' => $postname, 'postno' => $postno, 'status' => 2, 'sendtime' => time()]);
            $this->success('发货成功', url('seeOrder', ['id' => $param['id']]));
        }
        return view('', compact('id'));
    }

    //确定退款 申请处理
    public function doBackOrder()
    {
        $orderid = input('order_id', '', 'intval');
        //退款订单状态
        $status = input('status', 0, 'intval');
        if ($orderid == 0 || $status == 0) {
            $this->error('订单id错误');
        }
        //查询退款表id
        $orderData = db('market_order')->find($orderid);
        if ($orderData['status'] != 6) {
            $this->error('订单状态不允许');
        }
        $backid = $orderData['backid'];
        /*
         status 退款表状态:
            1、待发货，申请退款 //退还写入的金额以及订单使用的代币 和 库存 关闭订单 更改退款表状态6
            2、收货后，申请退款不退货  //退还写入的金额以及订单使用的代币和 关闭订单 更改退款表状态6
            3、退货退款 申请中 3  //更改退款状态表为4
            4、退货退款 申请通过 后台同意 //前台发货  更改退款状态表为5
            5、退货退款 后台同意之后 前台填写快递信息  //退还写入的金额以及订单使用的代币 和关闭订单 更改退款表状态为6
            6、完成退款
        */
        switch ($status) {
            case 1:
                //金额代币
                $this->backMoneyToken($backid);
                //库存
                $this->backSpec($orderid);
                //关闭订单
                $this->closeOrder($orderid);
                //更改退款表状态6
                $this->changeBackTable($backid, $status = 6);
                break;
            case 2:
                //退款不退货  退还写入的金额以及订单使用的代币和 关闭订单 更改退款表状态6
                //金额代币
                $this->backMoneyToken($backid);
                //关闭订单
                $this->closeOrder($orderid);
                //更改退款表状态6
                $this->changeBackTable($backid, $status = 6);
                break;
            case 3:
                //退货退款 申请中 3  //更改退款状态表为4
                //更改退款表状态6
                $this->changeBackTable($backid, $status = 4);
                break;
            case 5:
                //退货退款 后台同意之后 前台填写快递信息  //退还写入的金额以及订单使用的代币 和关闭订单 更改退款表状态为6
                //金额代币
                $this->backMoneyToken($backid);
                //关闭订单
                $this->closeOrder($orderid);
                //更改退款表状态6
                $this->changeBackTable($backid, $status = 6);
                break;
            default:
                $this->error('操作错误');
        }
        $this->success('操作成功');
    }

    //拒绝申请处理
    public function doReturnOrder()
    {
        $orderid = input('order_id', '', 'intval');
        if (empty($orderid)) {
            $this->error('参数错误');
        }
        //查询退款表id
        $orderData = db('market_order')->find($orderid);
        $backid = $orderData['backid'];
        $oldstatus = db('marketorder_back')->find($backid)['oldstatus'];
        //将订单状态更改为申请之前的状态 清除 backid
        Db::name('market_order')
            ->where('id', $orderid)
            ->update(['status' => $oldstatus, 'backid' => null]);
        $this->success('操作成功');
    }

    /**
     * 更改退款表状态
     * @param $backid 退款表id
     * @param $status 状态
     */
    private function changeBackTable($backid, $status)
    {
        Db::name('marketorder_back')
            ->where('id', $backid)
            ->setField('status', $status);
    }

    /**
     * 关闭订单
     * $order_id 订单id
     */
    private function closeOrder($orderid)
    {
        Db::name('market_order')
            ->where('id', $orderid)
            ->setField('status', 7);
    }

    /**
     * 退还写入的金额以及订单使用的代币
     * $backid 退款表id
     */
    private function backMoneyToken($backid)
    {
        //获取退款表数据
        $backData = db('marketorder_back')->find($backid);
        //获取订单的使用代币 和 用户uid
        $orderData = db('market_order')->find($backData['oid']);
        $uid = $orderData['uid'];
        $tokenMoney = $orderData['daibi'];
        $money = $backData['money'];
        //退还代币、
        Db::name('token_money')->where('user_id', $uid)->setInc('no_extract_num', $tokenMoney);
        //写入日志 $type=4订单取消退还
        TokenMoneyLogModel::putTokenLog($uid, $type = 4, $extract_num = 0, $no_extract_num = $tokenMoney, '退款返还');
        //退还金额
        Db::name('user')->where('id', $uid)->setInc('balance', 666);
        //写入日志
        MoneybagLogModel::writeMoneybagLog($uid, $money, 0, '退款返还');
    }

    /**
     * 库存
     * 根据订单id 退回该订单下的所有商品表的库存
     * $orderid 订单id
     */
    protected function backSpec($orderid)
    {
        $goods_id = db('market_order')->find($orderid)['goods_id'];
        $detailsDatas = db('market_order_details')->where('order_id', $orderid)->select();
        foreach ($detailsDatas as $detailsData) {
            $spec_str = $detailsData['spec_str'];
            $stock = $detailsData['stock'];
            Db::name('market_spec')
                ->where('goods_id', $goods_id)
                ->where('spec_str', $spec_str)
                ->setInc('stock', $stock);
        }
    }

    /*快递*/
    public function seePost()
    {
        $id = input('id');
        $orderData = db('market_order')->field('postname,postno')->find($id);

        if (empty($postname = $orderData['postname']) || empty($postno = $orderData['postno'])) {
            echo '请确认您填写的快递没问题';
            return;
        }
        $postData = db('post')->where('postname', 'like', "%{$postname}%")->find();
        if (!$postData) {
            echo '请确认您填写的快递没问题';
            return;
        }
        $postcode = $postData['postcode'];
        include_once '../vendor/post/post.php';
        $result = \post::index($postcode, $postno);
        $result = json_decode($result, true);
        if (true === $result['Success']) {
            $data = $result['Traces'];
        } else {
            $data = '';
        }
        return view('', compact('data'));
    }

}
